<?php
declare (strict_types = 1);

namespace app\controller\admin;


use app\common\AliOss;
use think\facade\Filesystem;
use think\response\Json;


class AdminUpload extends AdminBase
{

	protected $middleware = [
        'app\middleware\AdminLogin'
	];

	private string $menuName = '上传';

    /**
     * 上传图片
     * @throws
     * @return Json
     */
    public function image():Json
    {
        try {

            // 获取表单上传文件
            $files = $this->request->file();
            if (!$files || !count($files)) {
                throw new \Exception('未上传任何图片');
            }
            //大小限制 10MB
            $size = 10 * 1024 * 1024;
            //类型限制
            $ext = 'jpg,jpeg,png,gif,bmp,ico,webp';
            validate(['image' => 'fileSize:' . $size . '|fileExt:' . $ext . '|image:2000,2000'])
                ->check($files);

            $file = array_shift($files);

            // 移动到框架网站根目录/uploads/ 目录下
            $saveName = Filesystem::disk('public')->putFile('image', $file);
            $saveName = str_replace('\\','/',$saveName);

            $this->result['data'] = addDomain('/upload/'.$saveName);
            $this->request->setRoute(['filename'=>$saveName,'filesize'=>$this->getFileSize($file->getSize())]);
        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }

		return returnAdmin($this->request,$this->result,$this->menuName.'-图片',$this->adminInfo);
    }

    /**
     * 富文本编辑器上传图片
     * @throws
     * @return Json
     */
    public function imageEdit():Json
    {
        try {

            // 获取表单上传文件
            $files = $this->request->file();
            if (!$files || !count($files)) {
                throw new \Exception('未上传任何图片');
            }
            //大小限制 10MB
            $size = 10 * 1024 * 1024;
            //类型限制
            $ext = 'jpg,jpeg,png,gif,bmp,ico,webp';
            validate(['image' => 'fileSize:' . $size . '|fileExt:' . $ext . '|image:2000,2000'])
                ->check($files);

            $file = array_shift($files);
            // 移动到框架网站根目录/uploads/ 目录下
            $saveName = Filesystem::disk('public')->putFile('edit_image', $file);
            $saveName = str_replace('\\','/',$saveName);

            $this->result['data'] = [
                'url' => addDomain('/upload/'.$saveName),
                'alt' => '',
                'href' => ''
            ];
            $this->result['errno'] = 0;
            $this->request->setRoute(['filename'=>$saveName,'filesize'=>$this->getFileSize($file->getSize())]);
        }catch (\Exception $e){
            $this->result['code'] = $this->result['errno'] = 500;
            $this->result['msg'] = $this->result['message'] = $e->getMessage();
        }

        return returnAdmin($this->request,$this->result,$this->menuName.'-富文本图片',$this->adminInfo);
    }

    /**
     * 上传视频
     * @throws
     * @return Json
     */
    public function video():Json
    {
        try {

            // 获取表单上传文件
            $files = $this->request->file();

            if (!$files || !count($files)) {
                throw new \Exception('未上传任何视频');
            }
            //大小限制 500MB
            $size = 500 * 1024 * 1024;
            //类型限制
            $ext = 'mp4,avi,mov,ts,webm,ogg,mp3';
            validate(['file' => 'fileSize:' . $size . '|fileExt:' . $ext ])->check($files);

            $file = array_shift($files);
            // 移动到框架网站根目录/uploads/ 目录下
            $saveName = Filesystem::disk('public')->putFile('video', $file);

            $saveName = str_replace('\\','/',$saveName);

            $this->result['data'] = addDomain('/upload/'.$saveName);
            $this->request->setRoute(['filename'=>$saveName,'filesize'=>$this->getFileSize($file->getSize())]);
        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }
        return returnAdmin($this->request,$this->result,$this->menuName.'-视频',$this->adminInfo);
    }

    /**
     * 富文本编辑器上传视频
     * @throws
     * @return Json
     */
    public function videoEdit():Json
    {
        try {

            // 获取表单上传文件
            $files = $this->request->file();

            if (!$files || !count($files)) {
                throw new \Exception('未上传任何视频');
            }
            //大小限制 500MB
            $size = 500 * 1024 * 1024;
            //类型限制
            $ext = 'mp4,avi,mov,ts,webm,ogg,mp3';
            validate(['file' => 'fileSize:' . $size . '|fileExt:' . $ext ])->check($files);

            $file = array_shift($files);
            // 移动到框架网站根目录/uploads/ 目录下
            $saveName = Filesystem::disk('public')->putFile('edit_video', $file);

            $saveName = str_replace('\\','/',$saveName);

            $this->result['data'] = [
                'url' => addDomain('/upload/'.$saveName),
                'poster' => ''
            ];

            $this->result['errno'] = 0;
            $this->request->setRoute(['filename'=>$saveName,'filesize'=>$this->getFileSize($file->getSize())]);
        }catch (\Exception $e){
            $this->result['code'] = $this->result['errno'] = 500;
            $this->result['msg'] = $this->result['message'] = $e->getMessage();
        }
        return returnAdmin($this->request,$this->result,$this->menuName.'-富文本视频',$this->adminInfo);
    }

    /**
     * 上传文件
     * @throws
     * @return Json
     */
    public function file():Json
    {
        try {

            // 获取表单上传文件
            $files = $this->request->file();
            if (!$files || !count($files)) {
                throw new \Exception('未上传任何文件');
            }
            //大小限制 500MB
            $size = 500 * 1024 * 1024;
            //类型限制
            $ext = 'txt,doc,docs,docx,xls,xlsx,csv,ppt,pdf,odt,ott,apk,otf,ttf,fodt,uot,xml,dot,rtf,docm,zip,rar,tar,7z,tar.gz,tar.bz,tar.xz,dwg,dxf,dwt,pem';
            validate(['file' => 'fileSize:' . $size . '|fileExt:' . $ext ])->check($files);

            $file = array_shift($files);
            // 移动到框架网站根目录/uploads/ 目录下
            $saveName = Filesystem::disk('public')->putFile('file', $file);
            $saveName = str_replace('\\','/',$saveName);

            $this->result['data'] = addDomain('/upload/'.$saveName);
            $this->request->setRoute(['filename'=>$saveName,'filesize'=>$this->getFileSize($file->getSize())]);
        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }

        return returnAdmin($this->request,$this->result,$this->menuName.'-文件',$this->adminInfo);
    }

    /**
     * 获取文件大小
     * @param int $size 文件大小（b）
     *
     * @return string
     * */
    private function getFileSize(int $size):string
    {
        $unit = 'KB';
        if($size){
            $size = bc($size , 1024,4);
            if($size > 1024){
                $size = bc($size , 1024,4);
                $unit = 'MB';
                if($size > 1024){
                    $size = bc($size , 1024,4);
                    $unit = 'GB';
                    if($size > 1024){
                        $size = bc($size , 1024,4);
                        $unit = 'TB';
                    }
                }
            }
        }
        return $size.$unit;
    }

    /**
     * 上传图片接口
     * @throws
     * @return Json
     */
    public function ueditor():Json{
        $actionName = input('requestType','config');

        $config = [
            // 图片上传配置
            // 执行上传图片的action名称，默认值：image
            "imageActionName"=> "image",
            // 提交的图片表单名称，默认值：upfile
            "imageFieldName"=> "file",
            // 上传大小限制，单位B，默认值：2048000
            "imageMaxSize"=> 10485760,
            // 上传图片格式显示，默认值：[".png", ".jpg", ".jpeg", ".gif", ".bmp"]
            "imageAllowFiles"=> [
                ".png", ".jpg", ".jpeg", ".gif", ".bmp"
            ],
            // 是否压缩图片,默认是true
            "imageCompressEnable"=> true,
            // 图片压缩最长边限制，默认值：1600
            "imageCompressBorder"=> 5000,
            // 插入的图片浮动方式，默认值：none
            "imageInsertAlign"=> "none",
            // 图片访问路径前缀，默认值：空
            "imageUrlPrefix"=> "",

            // 图片列表配置
            // 执行图片管理的action名称，默认值：listImage
            "imageManagerActionName"=> "listImage",
            // 每次列出文件数量
            "imageManagerListSize"=> 20,
            // 图片访问路径前缀
            "imageManagerUrlPrefix"=> "",
            // 插入的图片浮动方式，默认值：none
            "imageManagerInsertAlign"=> "none",
            // 列出的文件类型
            "imageManagerAllowFiles"=> [
                ".jpg",
                ".png",
                ".jpeg"
            ],

            // 视频上传配置
            // 执行上传视频的action名称，默认值：video
            "videoActionName"=> "video",
            // 提交的视频表单名称，默认值：file
            "videoFieldName"=> "file",
            // 视频访问路径前缀
            "videoUrlPrefix"=> "",
            // 上传大小限制，单位B，默认值：102400000
            "videoMaxSize"=> 104857600,
            // 上传视频格式显示
            "videoAllowFiles"=> [".mp4"],

            // 文件上传配置
            // 执行上传文件的action名称，默认值：file
            "fileActionName"=> "file",
            // 提交的文件表单名称，默认值：file
            "fileFieldName"=> "file",
            // 文件访问路径前缀
            "fileUrlPrefix"=> "",
            // 上传保存路径,可以自定义保存路径和文件名格式，默认值：{filename}{rand:6}
            "fileMaxSize"=> 104857600,
            // 上传文件格式显示
            "fileAllowFiles"=> [".zip",".pdf",".doc"],

            // 公式配置
            "formulaConfig"=> [
                // 公式渲染的路径
                "imageUrlTemplate"=> "https://r.latexeasy.com/image.svg?{}"
            ]
        ];

        $result = [
            'state'=> "SUCCESS",
            'url'=> "",
            'title'=> "",
            'original'=> ""
        ];

        if($actionName === 'config'){

            return jJson($config);
        }elseif($actionName === 'image'){
            try {
                // 获取表单上传文件
                $files = $this->request->file();
                if (!$files || !count($files)) {
                    throw new \Exception('未上传任何图片');
                }

                $fk = array_key_first($files);

                //大小限制 10MB
                $size = 10 * 1024 * 1024;
                //类型限制
                $ext = 'jpg,jpeg,png,gif,bmp,ico,webp';

                validate([$fk => 'fileSize:' . $size . '|fileExt:' . $ext ])->check($files);

                $file = array_shift($files);

                $name = $file->hashName();
                $fileUrl = $file->getRealPath();
                $saveName = 'upload/image/'.$name;
                $result['title'] = $name;
                $result['original'] = $name;
                $result['url'] = AliOss::upload($fileUrl, $saveName);
                // 移动到框架网站根目录/uploads/ 目录下
                //$saveName = Filesystem::disk('public')->putFile('user/image', $file);
                //$link = '/upload/'.str_replace('\\','/',$saveName);

                //$this->thumb('.' . $link);
                /*if (!Wechat::imgSecCheck( '.' . $link)) {
                    unlink('.'.$link);
                    throw new \ValidateException('图片含有违规内容') ;
                }*/

                //$this->result['data'] = addDomain($link);


            }catch (\Exception $e){
                $result['state'] = 'error';

            }
            return jJson($result);
        }elseif($actionName === 'video'){
            try {
                // 获取表单上传文件
                $files = $this->request->file();
                if (!$files || !count($files)) {
                    throw new \Exception('未上传任何视频');
                }

                $fk = array_key_first($files);

                //大小限制 500MB
                $size = 500 * 1024 * 1024;
                //类型限制
                $ext = 'mp4,avi,mov,ts,webm,ogg,mp3';

                validate([$fk => 'fileSize:' . $size . '|fileExt:' . $ext ])->check($files);

                $file = array_shift($files);

                $name = $file->hashName();
                $fileUrl = $file->getRealPath();
                $saveName = 'upload/video/'.$name;
                $result['title'] = $name;
                $result['original'] = $name;
                $result['url'] = AliOss::upload($fileUrl, $saveName);
                // 移动到框架网站根目录/uploads/ 目录下
                //$saveName = Filesystem::disk('public')->putFile('user/video', $file);
                //$link = '/upload/'.str_replace('\\','/',$saveName);

                //$this->thumb('.' . $link);
                /*if (!Wechat::imgSecCheck( '.' . $link)) {
                    unlink('.'.$link);
                    throw new \ValidateException('图片含有违规内容') ;
                }*/

                //$this->result['data'] = addDomain($link);


            }catch (\Exception $e){
                $result['state'] = 'error';

            }
            return jJson($result);
        }else{
            return jJson($result);
        }
    }

}
